package co.yixiang.yshop.module.system.service.roleauthdata;

import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.module.system.controller.admin.roleauthdata.vo.SysRoleAuthDataPageReqVO;
import co.yixiang.yshop.module.system.dal.dataobject.roleauthdata.SysRoleAuthDataDO;
import co.yixiang.yshop.module.system.dal.mysql.roleauthdata.SysRoleAuthDataMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;



/**
 * 角色权限数据 Service 实现类
 *
 * @author yixiang
 */
@Service
@Validated
public class SysRoleAuthDataServiceImpl implements SysRoleAuthDataService {

    @Resource
    private SysRoleAuthDataMapper roleAuthDataMapper;

    @Override
    public List<SysRoleAuthDataDO> getRoleAuthDataList(SysRoleAuthDataPageReqVO pageReqVO) {
        return roleAuthDataMapper.selectList(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRoleAuthData(Integer userId, List<Long> storeIds, Integer dataTypeId) {
        // 1. 先删除该用户的所有仓库权限
        roleAuthDataMapper.deleteByRoleId(userId,dataTypeId);
        
        // 2. 批量插入新的权限数据
        if (storeIds != null && !storeIds.isEmpty()) {
            List<SysRoleAuthDataDO> authDataList = storeIds.stream()
                    .map(storeId -> SysRoleAuthDataDO.builder()
                            .userId(userId) // 角色权限，用户ID为空
                            .nodeId(storeId.toString()) // 仓库ID作为节点ID
                            .dataTypeId(dataTypeId)
                            .levelId(1)
                            .authValue(""+1)
                            .build())
                    .collect(Collectors.toList());
            
            roleAuthDataMapper.insertBatch(authDataList);
        }
    }

} 